/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

public class ReflectionUtil {

    /**
     * Get all public methods
     *
     * @param clazz class
     * @return All public methods of this class
     */
    public static Method[] getPublicMethod(Class<?> clazz) {
        Method[] methods = clazz.getMethods();

        ArrayList<Method> retList = new ArrayList<>();
        for (Method m : methods) {
            //Determine whether it is a common attribute
            if (Modifier.isPublic(m.getModifiers())) {
                retList.add(m);
            }
        }
        return retList.toArray(new Method[0]);
    }

    /**
     * Generate an instance of the class
     *
     * @param clazz class
     * @return instance of the class
     */
    public static <T> T newInstance(Class<T> clazz) {
        try {
            return (T) clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Reflection call method
     *
     * @param object The instance to which the method belongs
     * @param method method
     * @param args   Parameters of the method
     * @return The result of calling the method
     */
    public static Object invoke(Object object, Method method, Object... args) {

        try {
            for (Object arg : args) {
                System.out.println(arg.getClass().getName());
            }
            return method.invoke(object, args);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
